package com.ulic.customerManApplication.membermodule.action;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ulic.customerManApplication.base.BaseAction;
import com.ulic.customerManApplication.commonmodule.service.OrganizationService;
import com.ulic.customerManApplication.commonmodule.vo.ImpDataInfor;
import com.ulic.customerManApplication.constant.CONSTANT;
import com.ulic.customerManApplication.journeylovemodule.bo.JourneyOfLoveActivity;
import com.ulic.customerManApplication.journeylovemodule.service.JourneyLoveService;
import com.ulic.customerManApplication.membermodule.bo.Member;
import com.ulic.customerManApplication.membermodule.bo.SubMember;
import com.ulic.customerManApplication.membermodule.service.MemberService;
import com.ulic.customerManApplication.membermodule.service.SubMemberService;
import com.ulic.customerManApplication.membermodule.vo.SubMemberVO;
import com.ulic.customerManApplication.pager.PagerModel;
import com.ulic.customerManApplication.usermodule.bo.User;
import com.ulic.customerManApplication.util.config.ConfigInfo;
import com.ulic.customerManApplication.util.excel.DownloadDemo;
import com.ulic.customerManApplication.util.excel.DownloadExcel;
import com.ulic.customerManApplication.util.excel.ExpSubMembers;
import com.ulic.customerManApplication.util.excel.UploadFile;
@Component("subMemberAction")
@Scope("prototype")
public class SubMemberAction extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
    private SubMemberService subMemberService;
    private SubMember subMember;
    private SubMember preUpdateSubMember;
    private User user;
    private ImpDataInfor impDataInfor = new ImpDataInfor();
    Map<Integer,String> warnOrFailReason = new TreeMap<Integer,String>();
    private String impDataInfo;
    private JourneyOfLoveActivity journeyLove;
    private String journeyLoveId;
    private File membersFile;
    private String fileName;
    private OrganizationService organizationService;
    private JourneyLoveService journeyLoveService;
    private MemberService memberService;
    private String startbirthday;
    private String endbirthday;
    private String startcreate;
    private String endcreate;
    
    private String subCityHidden;
	
	public String getSubCityHidden() {
		return subCityHidden;
	}
	public void setSubCityHidden(String subCityHidden) {
		this.subCityHidden = subCityHidden;
	}
    
	public void setJourneyLove(JourneyOfLoveActivity journeyLove) {
		this.journeyLove = journeyLove;
	}
	public JourneyOfLoveActivity getJourneyLove() {
		return journeyLove;
	}
	public SubMemberService getSubMemberService() {
		return subMemberService;
	}
	@Resource
	public void setSubMemberService(SubMemberService subMemberService) {
		this.subMemberService = subMemberService;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public ImpDataInfor getImpDataInfor() {
		return impDataInfor;
	}
	public void setImpDataInfor(ImpDataInfor impDataInfor) {
		this.impDataInfor = impDataInfor;
	}
	
	public Map<Integer, String> getWarnOrFailReason() {
		return warnOrFailReason;
	}
	public void setWarnOrFailReason(Map<Integer, String> warnOrFailReason) {
		this.warnOrFailReason = warnOrFailReason;
	}
	public String getImpDataInfo() {
		return impDataInfo;
	}
	public void setImpDataInfo(String impDataInfo) {
		this.impDataInfo = impDataInfo;
	}
	public SubMember getSubMember() {
		return subMember;
	}
	public void setSubMember(SubMember subMember) {
		this.subMember = subMember;
	}
	public File getMembersFile() {
		return membersFile;
	}
	public void setMembersFile(File membersFile) {
		this.membersFile = membersFile;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	 
	public SubMember getPreUpdateSubMember() {
		return preUpdateSubMember;
	}
	public void setPreUpdateSubMember(SubMember preUpdateSubMember) {
		this.preUpdateSubMember = preUpdateSubMember;
	}
	public void setStartbirthday(String startbirthday) {
		this.startbirthday = startbirthday;
	}
	public void setEndbirthday(String endbirthday) {
		this.endbirthday = endbirthday;
	}
	public void setStartcreate(String startcreate) {
		this.startcreate = startcreate;
	}
	public void setEndcreate(String endcreate) {
		this.endcreate = endcreate;
	}
	public String getStartbirthday() {
		return startbirthday;
	}
	public String getEndbirthday() {
		return endbirthday;
	}
	public String getStartcreate() {
		return startcreate;
	}
	public String getEndcreate() {
		return endcreate;
	}
	public String getJourneyLoveId() {
		return journeyLoveId;
	}
	public void setJourneyLoveId(String journeyLoveId) {
		this.journeyLoveId = journeyLoveId;
	}
	@Resource
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	@Resource
	public void setJourneyLoveService(JourneyLoveService journeyLoveService) {
		this.journeyLoveService = journeyLoveService;
	}
	
	public JourneyLoveService getJourneyLoveService() {
		return journeyLoveService;
	}
	@Resource
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
	
	public MemberService getMemberService() {
		return memberService;
	}
	@Override
	public String execute() throws Exception {
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		PagerModel pm = subMemberService.getSubMembers(curPage);
		httpServletRequest.setAttribute("pm",pm);
		return SUCCESS;
	}
	
	public String searchSubMembers(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		SubMemberVO subMemberVO = new SubMemberVO();
		String roleName = (String)session.get("rolename");
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		subMemberVO.setSubMember(subMember);
		subMemberVO.setRoleName(roleName);
		subMemberVO.setUser(user);
		subMemberVO.setStartbirthday(startbirthday);
		subMemberVO.setEndbirthday(endbirthday);
		subMemberVO.setStartcreate(startcreate);
		subMemberVO.setEndcreate(endcreate);
		subMemberVO.setJourneyLoveId(journeyLoveId);
		httpServletRequest.setAttribute("startcreate", startcreate);
		httpServletRequest.setAttribute("endcreate", endcreate);
		PagerModel pm = subMemberService.getSubMembers(subMemberVO, curPage);
		JourneyOfLoveActivity joActivity = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
		if(subMember==null){
			subMember = new SubMember();
		}
		subMember.setSubCompany(joActivity.getSubCompany());
		subMember.setSubCity(joActivity.getSubCity());
		subMember.setSubComName(joActivity.getSubComName());
		subMember.setSubCityName(joActivity.getSubCityName());
		httpServletRequest.setAttribute("pm",pm);
		httpServletRequest.setAttribute("journeyLoveId", Integer.parseInt(journeyLoveId));
		httpServletRequest.setAttribute("roleName", roleName);
		return SUCCESS;
	}
	public String toSaveSubMember()throws Exception{
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		JourneyOfLoveActivity joActivity = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
		if(subMember==null){
			subMember = new SubMember();
		}
		subMember.setSubCompany(joActivity.getSubCompany());
		subMember.setSubCity(joActivity.getSubCity());
		subMember.setSubComName(joActivity.getSubComName());
		subMember.setSubCityName(joActivity.getSubCityName());
		httpServletRequest.setAttribute("journeyLoveId", httpServletRequest.getParameter("journeyLoveId"));
		return SUCCESS;
		
	}
	public String saveSubMember()throws Exception{
		//判断输入是否合法
		checkInputValue(subMember,journeyLoveId);
		subMember.setSub_createDate(new Date());
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		subMember.setSub_user(user);
		JourneyOfLoveActivity jLove = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
		subMember.setSub_memberType(getMemberType(subMember.getSub_donateStuNum()));
		String type = addMember(subMember);
		subMember.setSub_memberType(type);
		if("绿卡会员".equals(subMember.getSub_memberType())){
			jLove.setGreenCardMember(jLove.getGreenCardMember()+1);
		}else if("银卡会员".equals(subMember.getSub_memberType())){
			jLove.setSilverCardMember(jLove.getSilverCardMember()+1);
		}else if("金卡会员".equals(subMember.getSub_memberType())){
			jLove.setGoldenCardMember(jLove.getGoldenCardMember()+1);
		}else if("金箔卡会员".equals(subMember.getSub_memberType())){
			jLove.setPlatinumCardMember(jLove.getPlatinumCardMember()+1);
		}else if("钻石卡会员".equals(subMember.getSub_memberType())){
			jLove.setDiamondCardMember(jLove.getDiamondCardMember()+1);
		}
	//	jLove.setDonateStuNum(jLove.getDonateStuNum()+subMember.getSub_donateStuNum());
		subMember.setSub_journeyOfLoveActivity(jLove);
		subMemberService.addSubMember(subMember);
		journeyLoveService.modifyJourneyLove(jLove);
		this.journeyLoveId = jLove.getId()+"";
		recache();
		return SUCCESS;
	}
	/**
	 * Description: 判断
	 * @Version1.0 
	 * 2013-8-29 上午10:01:05 李求智 (liqz@huilan.com) created
	 * @throws Exception
	 */
	private void checkInputValue(SubMember subMember,String journeyLoveId) throws Exception{
		if(subMember == null){
			throw new Exception("传入参数丢失请重新提交！");
		}else if(subMember.getSub_memberName() == null || subMember.getSub_memberName().length() == 0){
			throw new Exception("会员姓名不能为空！");
		}else if(subMember.getSub_gender() == null || subMember.getSub_gender().length() == 0){
			throw new Exception("会员性别不能为空！");
		}else if(subMember.getSub_cellPhone() == null || subMember.getSub_cellPhone().length() == 0){
			throw new Exception("会员手机号码不能为空！");
		}else if(!checkPhone(subMember.getSub_cellPhone())){
			throw new Exception("会员手机号码格式错误！");
		}else if(subMember.getSub_donateRecord() == null || subMember.getSub_donateRecord().length() == 0){
			throw new Exception("会员捐赠记录不能为空！");
		}else if(subMember.getSub_donateStuNum() == null || subMember.getSub_donateStuNum().toString().length() == 0){
			subMember.setSub_donateStuNum(0);
		}else if(!checkSub_donateStuNum(String.valueOf(subMember.getSub_donateStuNum()))){
			throw new Exception("捐助学生数必须为0和正整数！");
		}
		if(subMemberService.getSubMemberByPhone(subMember.getSub_cellPhone(),journeyLoveId) != null){
			throw new Exception("会员手机号码已经被其他会员使用，请更换手机号码！");
		}
	}
	/**
	 * Description: 判断是否是手机号码
	 * @Version1.0 
	 * 2013-8-29 上午10:14:58 李求智 (liqz@huilan.com) created
	 * @param phone
	 * @return
	 */
	public static boolean checkPhone(String phone){
		Pattern p=Pattern.compile("^1[3|4|5|8][0-9]\\d{8}$");
		Matcher m=p.matcher(phone);
		return m.find();
	}
	public static boolean checkEmail(String email){
		Pattern p = Pattern.compile("^\\w+((-\\w+)|(.\\w+))*@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$");
		Matcher m = p.matcher(email);
		return m.find();
	}
	public static boolean checkBirthday(String birthday){
		Pattern p=Pattern.compile("^\\d{4}-(\\d{2}|\\d{1})-(\\d{2}|\\d{1})$");
		Matcher m=p.matcher(birthday);
		return m.find();
	}
	/**
	 * Description: 判断是否是数字
	 * @Version1.0 
	 * 2013-8-29 上午10:31:07 李求智 (liqz@huilan.com) created
	 * @param num
	 * @return
	 */
	public static boolean checkSub_donateStuNum(String num){
		Pattern p=Pattern.compile("^\\d+$");
		Matcher m=p.matcher(num);
		return m.find();
	}
	public String viewSubMember()throws Exception{
		subMember = subMemberService.getSubMember(subMember.getSub_id());
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		httpServletRequest.setAttribute("journeyLoveId", httpServletRequest.getParameter("journeyLoveId"));
		return SUCCESS;
	}
	public String updateSubMember()throws Exception{
		subMember = subMemberService.getSubMember(subMember.getSub_id());
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		httpServletRequest.setAttribute("journeyLoveId", httpServletRequest.getParameter("journeyLoveId"));
		return SUCCESS;
	}
	
    public String updatedSubMember()throws Exception{
    	 boolean isPhone = false;
		 User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		 preUpdateSubMember =subMemberService.getSubMember(subMember.getSub_id());
		 subMember.setSub_user(user);
		 JourneyOfLoveActivity journeyLove = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
		 subMember.setSub_memberType(getMemberType(subMember.getSub_donateStuNum()));
			/*if("银卡会员".equals(subMember.getSub_memberType()) && "绿卡会员".equals(preUpdateSubMember.getSub_memberType())){
				journeyLove.setGreenCardMember(journeyLove.getGreenCardMember()-1);
				journeyLove.setSilverCardMember(journeyLove.getSilverCardMember()+1);
			}else if("金卡会员".equals(subMember.getSub_memberType())){
				if("绿卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setGreenCardMember(journeyLove.getGreenCardMember()-1);
					journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember()+1);
				}else if("银卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setSilverCardMember(journeyLove.getSilverCardMember()-1);
					journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember()+1);
				}
			}else if("金箔卡会员".equals(subMember.getSub_memberType())){
				if("绿卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setGreenCardMember(journeyLove.getGreenCardMember()-1);
					journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember()+1);
				}else if("银卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setSilverCardMember(journeyLove.getSilverCardMember()-1);
					journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember()+1);
				}else if("金卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember()-1);
					journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember()+1);
				}
			}else if("钻石卡会员".equals(subMember.getSub_memberType())){
				if("绿卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setGreenCardMember(journeyLove.getGreenCardMember()-1);
					journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember()+1);
				}else if("银卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setSilverCardMember(journeyLove.getSilverCardMember()-1);
					journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember()+1);
				}else if("金卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember()-1);
					journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember()+1);
				}else if("金箔卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember()-1);
					journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember()+1);
				}
			}*/
		// journeyLove.setDonateStuNum(journeyLove.getDonateStuNum()-preUpdateSubMember.getSub_donateStuNum()+subMember.getSub_donateStuNum());
		 Member member = null;
		 	if(subMember.getSub_cellPhone()!=null && subMember.getSub_cellPhone().length()!=0){
				member = memberService.getMember(2,subMember.getSub_cellPhone());
				isPhone = (member != null ? true : false);
			}else if(subMember.getSub_idCard()!=null && subMember.getSub_idCard().length()!=0){
				member = memberService.getMember(1,subMember.getSub_idCard());
			}else{
				member = null;
			}
		 if(member!=null){
			 member.setDonateStuNum(member.getDonateStuNum()-preUpdateSubMember.getSub_donateStuNum()+subMember.getSub_donateStuNum());
			 member.setMemberType(getMemberType(member.getDonateStuNum()));
			 if(member.getDonateStuNum()<0){
				 member.setDonateStuNum(0);
			 }
			 memberService.modifyMember(member);
			 subMember.setSub_memberType(member.getMemberType());
		 }
		 if(!subMember.getSub_memberType().equals(preUpdateSubMember.getSub_memberType())){
			    if("绿卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setGreenCardMember(journeyLove.getGreenCardMember()-1);
				}else if("银卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setSilverCardMember(journeyLove.getSilverCardMember()-1);
				}else if("金卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember()-1);
				}else if("金箔卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember()-1);
				}else if("钻石卡会员".equals(preUpdateSubMember.getSub_memberType())){
					journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember()-1);
				}
			    
			    if("绿卡会员".equals(subMember.getSub_memberType())){
					journeyLove.setGreenCardMember(journeyLove.getGreenCardMember()+1);
				}else if("银卡会员".equals(subMember.getSub_memberType())){
					journeyLove.setSilverCardMember(journeyLove.getSilverCardMember()+1);
				}else if("金卡会员".equals(subMember.getSub_memberType())){
					journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember()+1);
				}else if("金箔卡会员".equals(subMember.getSub_memberType())){
					journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember()+1);
				}else if("钻石卡会员".equals(subMember.getSub_memberType())){
					journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember()+1);
				}
		 }
		 subMember.setSub_journeyOfLoveActivity(journeyLove);
		 subMemberService.modifySubMember(subMember);
		 
		 SubMember smm = null;
		 if(isPhone){
			 for(SubMember sMember:subMemberService.getSubMemberByPhone(subMember.getSub_cellPhone())){
					if(sMember instanceof SubMember){
						smm = (SubMember)sMember;
						smm.setSub_memberType(subMember.getSub_memberType());
						subMemberService.modifySubMember(smm);
					}
				}
		 }else{
			for(SubMember sMember:subMemberService.getSubMembers(subMember.getSub_idCard())){
				if(sMember instanceof SubMember){
					smm = (SubMember)sMember;
					smm.setSub_memberType(subMember.getSub_memberType());
					subMemberService.modifySubMember(smm);
				}
			}
		 }
			if(journeyLove.getGreenCardMember()<0){
				journeyLove.setGreenCardMember(0);
			}
			if(journeyLove.getSilverCardMember()<0){
				journeyLove.setSilverCardMember(0);
			}
			if(journeyLove.getGoldenCardMember()<0){
				journeyLove.setGoldenCardMember(0);
			}
			if(journeyLove.getPlatinumCardMember()<0){
				journeyLove.setPlatinumCardMember(0);
			}
			if(journeyLove.getDiamondCardMember()<0){
				journeyLove.setDiamondCardMember(0);
			}
			if(journeyLove.getDonateStuNum()<0){
				journeyLove.setDonateStuNum(0);
			}
		 journeyLoveService.modifyJourneyLove(journeyLove);
		 this.journeyLoveId = journeyLove.getId()+"";
		 return SUCCESS;
	} 
	
	public String deleteSubMember()throws Exception{
		boolean isPhone = false;
		subMember = subMemberService.getSubMember(subMember.getSub_id());
		subMemberService.removeSubMember(subMember);
		JourneyOfLoveActivity journeyLove = journeyLoveService.getJourneyLoveById(subMember.getSub_journeyOfLoveActivity().getId());
		if("绿卡会员".equals(subMember.getSub_memberType())) {
			journeyLove.setGreenCardMember(journeyLove.getGreenCardMember()-1);
		}else if("银卡会员".equals(subMember.getSub_memberType())){
			journeyLove.setSilverCardMember(journeyLove.getSilverCardMember()-1);
		}else if("金卡会员".equals(subMember.getSub_memberType())){
			journeyLove.setGoldenCardMember(journeyLove.getGoldenCardMember()-1);
		}else if("金箔卡会员".equals(subMember.getSub_memberType())){
			journeyLove.setPlatinumCardMember(journeyLove.getPlatinumCardMember()-1);
		}else if("钻石卡会员".equals(subMember.getSub_memberType())){
			journeyLove.setDiamondCardMember(journeyLove.getDiamondCardMember()-1);
		}
		journeyLove.setDonateStuNum(journeyLove.getDonateStuNum()-subMember.getSub_donateStuNum());
		if(journeyLove.getGreenCardMember()<0){
			journeyLove.setGreenCardMember(0);
		}
		if(journeyLove.getSilverCardMember()<0){
			journeyLove.setSilverCardMember(0);
		}
		if(journeyLove.getGoldenCardMember()<0){
			journeyLove.setGoldenCardMember(0);
		}
		if(journeyLove.getPlatinumCardMember()<0){
			journeyLove.setPlatinumCardMember(0);
		}
		if(journeyLove.getDiamondCardMember()<0){
			journeyLove.setDiamondCardMember(0);
		}
		if(journeyLove.getDonateStuNum()<0){
			journeyLove.setDonateStuNum(0);
		}
		journeyLoveService.modifyJourneyLove(journeyLove);
		Member member = null;
		if(subMember.getSub_cellPhone()!=null && subMember.getSub_cellPhone().length()!=0){
			member = memberService.getMember(2,subMember.getSub_cellPhone());
			isPhone = member != null ? true : false;
		}else if(subMember.getSub_idCard()!=null && subMember.getSub_idCard().length()!=0){
			member = memberService.getMember(1,subMember.getSub_idCard());
		}else{
			member = null;
		}
		if(member!=null){
			member.setDonateStuNum(member.getDonateStuNum()-subMember.getSub_donateStuNum());
			if(member.getDonateStuNum()<0){
				member.setDonateStuNum(0);
			}
			member.setMemberType(getMemberType(member.getDonateStuNum()));
			memberService.modifyMember(member);
			SubMember smm = null;
			if(isPhone){
				for(SubMember sMember:subMemberService.getSubMemberByPhone(subMember.getSub_cellPhone())){
					if(sMember instanceof SubMember){
						smm = (SubMember)sMember;
						smm.setSub_memberType(member.getMemberType());
						subMemberService.modifySubMember(smm);
					}
				}
			}else{
				for(SubMember sMember:subMemberService.getSubMembers(subMember.getSub_idCard())){
					if(sMember instanceof SubMember){
						smm = (SubMember)sMember;
						smm.setSub_memberType(member.getMemberType());
						subMemberService.modifySubMember(smm);
					}
				}
			}
		}
		recache();
		this.journeyLoveId = journeyLove.getId()+"";
		return SUCCESS;
	}
	
	public String toImpSubMembers(){
		return SUCCESS;
	}
	
	/**public String impSubMembers() throws Exception{
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		long date = new Date().getTime();
		ImpDataInfor impDataInfor = new ImpDataInfor();
		List<Integer> errorNumbers = new ArrayList<Integer>();
		String realPath = ConfigInfo.getPropertiesValue("uploadfile.path");
		if(fileName != null && fileName.length() !=0){
			fileName = UploadFile.upload(membersFile, fileName,date);//先将文件上传到服务器
			File f = new File(realPath+"/"+fileName);  
			List<SubMember> subMembers = new ArrayList<SubMember>();
			SubMember subMember = null;
			JourneyOfLoveActivity journeyOfLoveActivity = null;
			try {   
				journeyOfLoveActivity = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
				FileInputStream is = new FileInputStream(f);  //读取服务器上的文件 
				HSSFWorkbook wbs = new HSSFWorkbook(is);   
				HSSFSheet childSheet = wbs.getSheetAt(0); 
				loop :	for (int j = 1; j <= childSheet.getLastRowNum(); j++) {   
						HSSFRow row = childSheet.getRow(j);   
						subMember = new SubMember();
						if (null != row) { 

							for (int k = 0; k < 13; k++) {   
								String value = null;
								int number = 0;
								HSSFCell cell = row.getCell((short)k);   
								if (null != cell) { 
									switch (cell.getCellType()) {   
									case HSSFCell.CELL_TYPE_NUMERIC: // 数字   
										System.out.print(cell.getNumericCellValue()   
												+ "   ");
										number = (int)cell.getNumericCellValue();
										break;   
									case HSSFCell.CELL_TYPE_STRING: // 字符串   
										System.out.print(cell.getStringCellValue()   
												+ "   "); 
										value = cell.getStringCellValue();
										break;   
									case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean   
										System.out.println(cell.getBooleanCellValue()   
												+ "   ");   
										break;   
									case HSSFCell.CELL_TYPE_FORMULA: // 公式   
										System.out.print(cell.getCellFormula() + "   ");   
										break;   
									case HSSFCell.CELL_TYPE_BLANK: // 空值   
										System.out.println(" ");   
										break;   
									case HSSFCell.CELL_TYPE_ERROR: // 故障   
										System.out.println(" ");   
										break;   
									default:   
										System.out.print("未知类型   ");   
										break;   
									} 
									
								} else {   
									System.out.print("-   ");   
									value="";
								} 
								switch(k){
								case 0:
									subMember.setSub_memberName(value);
									break;
								case 1:
									subMember.setSub_gender(value);
									break;
								case 2:
									subMember.setSub_idCard(value);
									break;
								case 3:
									subMember.setSub_birthday(value);
									break;
								case 4:
									subMember.setSub_cellPhone(value);
									break;
								case 5:
									subMember.setSub_email(value);
									break;
								case 6:
									subMember.setSub_memberType(value);
									break;
								case 7:
									subMember.setSub_carBrand(value);
									break;
								case 8:
									subMember.setSub_carType(value);
									break;
								case 9:
									subMember.setSub_donateStuNum(number);
									break;
								
								case 10:
									subMember.setSub_donateRecord(value);
									break;
								case 11:
									subMember.setSub_reproduceIntroduce(value);
									break;
								case 12:
									subMember.setSub_forumPosting(value);
									break;
								case 13:
									subMember.setSub_remark(value);
									break;
								default:  
									break;
								}
							}   
						}
						subMember.setSub_createDate(new Date()); 
						subMember.setSub_user(user);
					 
						if(subMember.getSub_cellPhone()!=null && subMember.getSub_cellPhone().length()!=0 ){
							subMember.setSub_journeyOfLoveActivity(journeyOfLoveActivity);
							System.out.println("----------------->>>>>>"+subMember.getSub_memberName());
							subMember.setSub_memberType(getMemberType(subMember.getSub_donateStuNum()));
							//	journeyOfLoveActivity.setDonateStuNum(journeyOfLoveActivity.getDonateStuNum()+subMember.getSub_donateStuNum());
							 //根据爱心之旅的分公司和中支，设置活动产生会员的分公司和中支
							subMember.setSubCompany(journeyOfLoveActivity.getSubCompany());
							subMember.setSubCity(journeyOfLoveActivity.getSubCity());
							subMember.setSubComName(journeyOfLoveActivity.getSubComName());
							subMember.setSubCityName(journeyOfLoveActivity.getSubCityName());
							String type = addMember(subMember);
							subMember.setSub_memberType(type);
							subMembers.add(subMember);
						}else{
							errorNumbers.add(j);
						}
					}
//					List<SubMember> subs = subMemberService.getSubMembersByJourId(Integer.parseInt(journeyLoveId));
				    for(SubMember sub : subMembers){
				    	if("绿卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setGreenCardMember(journeyOfLoveActivity.getGreenCardMember()+1);
				    	}else if("银卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setSilverCardMember(journeyOfLoveActivity.getSilverCardMember()+1);
				    	}else if("金卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setGoldenCardMember(journeyOfLoveActivity.getGoldenCardMember()+1);
				    	}else if("金箔卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setPlatinumCardMember(journeyOfLoveActivity.getPlatinumCardMember()+1);
				    	}else if("钻石卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setDiamondCardMember(journeyOfLoveActivity.getDiamondCardMember()+1);
				    	}
				    }
				    subMemberService.addSubMembers(subMembers);//将从文件读取到的数据封装到对象 持久化到数据库
				    journeyLoveService.modifyJourneyLove(journeyOfLoveActivity);
					
					impDataInfor.setTotalNum(childSheet.getLastRowNum());
					impDataInfor.setSucceedNum(subMembers.size());
					impDataInfor.setFailNum(childSheet.getLastRowNum()-subMembers.size());
					String errorDetail = "";
					if(errorNumbers.size()!=0){
						for(Integer num : errorNumbers){
							errorDetail = errorDetail+num+" ";
						}
					}
					impDataInfor.setFailDetail(errorDetail);
					impDataInfor.setFailResaon("1");
			} catch (Exception e) {   
				e.printStackTrace();   
			} 
		}
        recache();
        this.setImpDataInfor(impDataInfor.toString());
		return SUCCESS;
	}*/
	public String impSubMembers() throws Exception{
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		long date = new Date().getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String realPath = ConfigInfo.getPropertiesValue("uploadfile.path");
		if(fileName != null && fileName.length() !=0){
			fileName = UploadFile.upload(membersFile, fileName,date);//先将文件上传到服务器
			File f = new File(realPath+"/"+fileName);  
			List<SubMember> subMembers = new ArrayList<SubMember>();
			SubMember subMember = null;
			JourneyOfLoveActivity journeyOfLoveActivity = null;
			try {   
				journeyOfLoveActivity = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
				FileInputStream is = new FileInputStream(f);  //读取服务器上的文件 
				HSSFWorkbook wbs = new HSSFWorkbook(is);   
				HSSFSheet childSheet = wbs.getSheetAt(0); 
				loop :	for (int j = 1; j <= childSheet.getLastRowNum(); j++) {   
						HSSFRow row = childSheet.getRow(j);   
						subMember = new SubMember();
						if (null != row) { 
							for (int k = 0; k < 13; k++) {   
								String value = "";
								HSSFCell cell = row.getCell((short)k);   
								if (null != cell) { 
									switch (cell.getCellType()) {   
									case HSSFCell.CELL_TYPE_NUMERIC: // 数字   
										System.out.print(cell.getNumericCellValue()   
												+ "   ");
										value = String.valueOf(cell.getNumericCellValue());
										break;   
									case HSSFCell.CELL_TYPE_STRING: // 字符串   
										System.out.print(cell.getStringCellValue()   
												+ "   "); 
										value = cell.getStringCellValue();
										break;   
									case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean   
										System.out.println(cell.getBooleanCellValue()   
												+ "   ");   
										value = String.valueOf(cell.getBooleanCellValue());
										break;   
									case HSSFCell.CELL_TYPE_FORMULA: // 公式   
										System.out.print(cell.getCellFormula() + "   ");   
										value = cell.getCellFormula();
										break;   
									case HSSFCell.CELL_TYPE_BLANK: // 空值   
										System.out.println(" ");   
										value = "";
										break;   
									case HSSFCell.CELL_TYPE_ERROR: // 故障   
										System.out.println(" ");   
										value = "";
										break;   
									default:   
										System.out.print("未知类型   ");   
										value = "";
										break;   
									} 
									
								} else {   
									System.out.print("-   ");   
									value="";
								} 
								switch(k){
								case 0:
									if(value == null && "".equals(value)){
										warnOrFailReason.put(j,"第" + j + "条数据：会员姓名为空，导入失败！");
										continue loop;
									}
									subMember.setSub_memberName(value);
									break;
								case 1:
									if(value == null && "".equals(value)){
										warnOrFailReason.put(j,"第" + j + "条数据：会员性别为空，导入失败！");
										continue loop;
									}
									subMember.setSub_gender(value);
									break;
								case 2:
									subMember.setSub_idCard(value);
									break;
								case 3:
									if("".equals(value.trim())){
										subMember.setSub_birthday("");
									}else if(!"".equals(value) && checkBirthday(value)){
										subMember.setSub_birthday(sdf.format(sdf.parse(value)));
									}else{
										subMember.setSub_birthday("");
										warnOrFailReason.put(j,"第" + j + "条数据：会员出生日期格式错误，已置为空值！");
									}
									break;
								case 4:
									if("".equals(value)){
										warnOrFailReason.put(j,"第" + j + "条数据：会员手机号码为空，导入失败！");
										continue loop;
									}else if(!checkPhone(value)){
										warnOrFailReason.put(j,"第" + j + "条数据：会员手机号码格式错误，导入失败！");
										continue loop;
									}else{
										subMember.setSub_cellPhone(value);
									}
									break;
								case 5:
									if(!"".equals(value) && !checkEmail(value)){
										subMember.setSub_email("");
										if(warnOrFailReason.containsKey(j)){
											warnOrFailReason.put(j,warnOrFailReason.get(j)+",会员电子邮件格式错误，已置为空值！");
										}else{
											warnOrFailReason.put(j,"第" + j + "条数据：会员电子邮件格式错误，已置为空值！");
										}
									}else{
										subMember.setSub_email(value);
									}
									break;
								case 7:
									subMember.setSub_carBrand(value);
									break;
								case 8:
									subMember.setSub_carType(value);
									break;
								case 9:
									try {
										if(!checkSub_donateStuNum(String.valueOf(Double.valueOf(value).intValue()))){
											subMember.setSub_donateStuNum(0);
											if(warnOrFailReason.containsKey(j)){
												warnOrFailReason.put(j,warnOrFailReason.get(j)+",会员捐赠学生数量格式错误，必须为0或正整数，已置为0！");
											}else{
												warnOrFailReason.put(j,"第" + j + "条数据：会员捐赠学生数量格式错误，必须为0或正整数，已置为0！");
											}
										}else{
											subMember.setSub_donateStuNum(Double.valueOf(value).intValue());
										}
									} catch (Exception e) {
										subMember.setSub_donateStuNum(0);
										if(warnOrFailReason.containsKey(j)){
											warnOrFailReason.put(j,warnOrFailReason.get(j)+",会员捐赠学生数量格式错误，必须为0或正整数，已置为0！");
										}else{
											warnOrFailReason.put(j,"第" + j + "条数据：会员捐赠学生数量格式错误，必须为0或正整数，已置为0！");
										}
									}
									break;
								case 10:
									subMember.setSub_donateRecord(value);
									break;
								case 11:
									subMember.setSub_reproduceIntroduce(value);
									break;
								case 12:
									subMember.setSub_forumPosting(value);
									break;
								case 13:
									subMember.setSub_remark(value);
									break;
								default:  
									break;
								}
							}   
						}
						if(subMemberService.getSubMemberByPhone(subMember.getSub_cellPhone(),journeyLoveId) != null){
							warnOrFailReason.put(j,"第" + j + "条数据：会员手机号码已经被其他会员使用，请更换手机号码！");
							continue loop;
						}
						Member member = memberService.getMember(2,subMember.getSub_cellPhone());
						if(member != null && !member.getMemberName().equals(subMember.getSub_memberName())){
							warnOrFailReason.put(j,"第" + j + "条数据：会员手机号码已经被其他会员使用，请更换手机号码！");
							continue loop;
						}
						subMember.setSub_createDate(new Date()); 
						subMember.setSub_user(user);
						subMember.setSub_journeyOfLoveActivity(journeyOfLoveActivity);
						System.out.println("----------------->>>>>>"+subMember.getSub_memberName());
						subMember.setSub_memberType(getMemberType(subMember.getSub_donateStuNum()));
						//	journeyOfLoveActivity.setDonateStuNum(journeyOfLoveActivity.getDonateStuNum()+subMember.getSub_donateStuNum());
						 //根据爱心之旅的分公司和中支，设置活动产生会员的分公司和中支
						subMember.setSubCompany(journeyOfLoveActivity.getSubCompany());
						subMember.setSubCity(journeyOfLoveActivity.getSubCity());
						subMember.setSubComName(journeyOfLoveActivity.getSubComName());
						subMember.setSubCityName(journeyOfLoveActivity.getSubCityName());
						//保存会员
						String type = addMember(subMember);
						subMember.setSub_memberType(type);
						subMemberService.addSubMember(subMember);//将从文件读取到的数据封装到对象 持久化到数据库
						subMembers.add(subMember);
					}
//					List<SubMember> subs = subMemberService.getSubMembersByJourId(Integer.parseInt(journeyLoveId));
				    for(SubMember sub : subMembers){
				    	if("绿卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setGreenCardMember(journeyOfLoveActivity.getGreenCardMember()+1);
				    	}else if("银卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setSilverCardMember(journeyOfLoveActivity.getSilverCardMember()+1);
				    	}else if("金卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setGoldenCardMember(journeyOfLoveActivity.getGoldenCardMember()+1);
				    	}else if("金箔卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setPlatinumCardMember(journeyOfLoveActivity.getPlatinumCardMember()+1);
				    	}else if("钻石卡会员".equals(sub.getSub_memberType())){
				    		journeyOfLoveActivity.setDiamondCardMember(journeyOfLoveActivity.getDiamondCardMember()+1);
				    	}
				    }
				    journeyLoveService.modifyJourneyLove(journeyOfLoveActivity);
					impDataInfor.setTotalNum(childSheet.getLastRowNum());
					impDataInfor.setSucceedNum(subMembers.size());
					impDataInfor.setFailNum(childSheet.getLastRowNum()-subMembers.size());
					impDataInfor.setDetail(warnOrFailReason);
					impDataInfo = impDataInfor.toString();
					ServletActionContext.getRequest().getSession().setAttribute("impDataInfor", impDataInfor);
			} catch (Exception e) {   
				e.printStackTrace();   
			} 
		}
        recache();
		return SUCCESS;
	}
	
	public String expSubMembers(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
		String realPath = httpServletRequest.getRealPath("/download/");
		String fileName = "会员信息.xls";
		String[] headers = {"分公司","中支","姓名","性别","身份证号","生日","手机","电子邮件","会员类型","车辆品牌","兴趣爱好","捐助学生数","捐赠记录","转介绍记录","发帖记录","备注"}; 
		List<SubMember> subMembers = subMemberService.getSubMembersByJourId(Integer.parseInt(journeyLoveId));
		ExpSubMembers.exp(headers,subMembers,realPath+"/"+fileName);//将数据读取到服务器上的文件中
	    DownloadExcel.download(realPath,fileName,httpServletRequest,httpServletResponse);//从服务器上下载文件
		return null;
	}
	
	public String expDemo(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
		String realPath = httpServletRequest.getRealPath("/download/");
		DownloadDemo.download(realPath,"MemberDemo.xls;会员信息模板.xls",httpServletRequest,httpServletResponse);//从服务器上下载文件
		return null;
	}
	
	public String addMember (SubMember subMember)throws Exception{
		boolean isPhone = false;
		Member member = null;
		if(subMember.getSub_cellPhone()!=null && subMember.getSub_cellPhone().length()!=0){
			member = memberService.getMember(2,subMember.getSub_cellPhone());
			if(member != null && !member.getMemberName().equals(subMember.getSub_memberName())){
				throw new Exception("手机号码已经被其他会员使用，请更换手机号码！");
			}
			isPhone = (member != null ? true : false);
		}else if(subMember.getSub_idCard()!=null && subMember.getSub_idCard().length()!=0){
			member = memberService.getMember(1,subMember.getSub_idCard());
		}else{
			return subMember.getSub_memberType();
		}
		if(member == null){
			member = new Member();
			member.setBirthday(subMember.getSub_birthday());
			member.setCarBrand(subMember.getSub_carBrand());
			member.setCarType(subMember.getSub_carType());
			member.setCellPhone(subMember.getSub_cellPhone());
			member.setCreateDate(subMember.getSub_createDate());
			member.setDonateRecord(subMember.getSub_donateRecord());
			member.setDonateStuNum(subMember.getSub_donateStuNum());
			member.setEmail(subMember.getSub_email());
			member.setForumPosting(subMember.getSub_forumPosting());
			member.setGender(subMember.getSub_gender());
			member.setIdCard(subMember.getSub_idCard());
			member.setMemberName(subMember.getSub_memberName());
			member.setMemberType(subMember.getSub_memberType());
			member.setSubCompany(subMember.getSubCompany());
			member.setSubCity(subMember.getSubCity());
			member.setSubComName(subMember.getSubComName());
			member.setSubCityName(subMember.getSubCityName());
			member.setRemark(subMember.getSub_remark());
			member.setReproduceIntroduce(subMember.getSub_reproduceIntroduce());
			member.setUser(subMember.getSub_user());
			memberService.addMember(member);
		}else{
			member.setDonateStuNum(member.getDonateStuNum()+subMember.getSub_donateStuNum());
            member.setMemberType(getMemberType(member.getDonateStuNum()));	
            if(!(member.getCellPhone()!=null && member.getCellPhone().length()!=0)){
            	member.setCellPhone(subMember.getSub_cellPhone());
            }
            if(!(member.getBirthday()!=null && member.getBirthday().length()!=0)){
            	member.setBirthday(subMember.getSub_birthday());
            }
            if(!(member.getIdCard()!=null && member.getIdCard().length()!=0)){
            	member.setIdCard(subMember.getSub_idCard());
            }
            if(!(member.getEmail()!=null && member.getEmail().length()!=0)){
            	member.setEmail(subMember.getSub_email());
            }
			memberService.modifyMember(member);
			SubMember smm = null;
			if(isPhone){
				for(SubMember sMember:subMemberService.getSubMemberByPhone(subMember.getSub_cellPhone())){
					if(sMember instanceof SubMember){
						smm = (SubMember)sMember;
						smm.setSub_memberType(member.getMemberType());
						subMemberService.modifySubMember(smm);
					}
				}
			}else{
				for(SubMember sMember:subMemberService.getSubMembers(subMember.getSub_idCard())){
					if(sMember instanceof SubMember){
						smm = (SubMember)sMember;
						smm.setSub_memberType(member.getMemberType());
						subMemberService.modifySubMember(smm);
					}
				}
			}
			
		}
		return member.getMemberType();
	}
	
	public String getMemberType(int dsnum){
		if(dsnum ==0){
			return "绿卡会员";
		}else if(dsnum>=1 && dsnum <= 3){
			return "银卡会员";
		}else if(dsnum>=4 && dsnum<=9){
			return "金卡会员";
		}else if(dsnum>=10 && dsnum<=20){
			return "金箔卡会员";
		}else{
			return "钻石卡会员";
		}
	}
	
}
